/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved. 
 */
package com.icinfo.cloud.provider.punish.execute.service.impl;

import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.common.documentoperate.enums.DocumentStatusEnum;
import com.icinfo.cloud.provider.punish.config.model.ConfigBusiParamDocumentInfo;
import com.icinfo.cloud.provider.punish.config.service.IConfigBusiParamDocumentInfoService;
import com.icinfo.cloud.provider.punish.execute.dto.SignExecuteReceiveDto;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteAppendixRecordMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecuteDocumentRecordMapper;
import com.icinfo.cloud.provider.punish.execute.mapper.ExecutePartyInfoMapper;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteAppendixRecord;
import com.icinfo.cloud.provider.punish.execute.model.ExecuteDocumentRecord;
import com.icinfo.cloud.provider.punish.execute.model.ExecutePartyInfo;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteAppendixRecordService;
import com.icinfo.cloud.provider.punish.execute.service.IExecuteDocumentRecordService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.mapper.CaseDocumentSendinfoConfirmMapper;
import com.icinfo.cloud.provider.punish.ucase.investigateevidence.model.CaseDocumentSendinfoConfirm;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 描述: 案件附件表-trj execute_appendix_record 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年09月06日
 */
@Service
@Slf4j
public class ExecuteAppendixRecordServiceImpl extends MyBatisServiceSupport implements IExecuteAppendixRecordService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(ExecuteAppendixRecordServiceImpl.class);

    @Autowired
    private ExecuteAppendixRecordMapper executeAppendixRecordMapper;
    @Autowired
    private ExecutePartyInfoMapper executePartyInfoMapper;
    @Autowired
    private ExecuteDocumentRecordMapper executeDocumentRecordMapper;

    @Autowired
    private IExecuteDocumentRecordService executeDocumentRecordService;
    @Autowired
    private IConfigBusiParamDocumentInfoService configBusiParamDocumentInfoService;

    @Resource
    private CaseDocumentSendinfoConfirmMapper caseDocumentSendinfoConfirmMapper;


    /**
     * 上传线下已签署文书-案源
     * @author liyafeng
     * @date 2022/8/18
     * @param signReceiveDto
     * @return {@link Map < Object, Object>}
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveOfflineSignFile(SignExecuteReceiveDto signReceiveDto) {
        if(ObjectUtils.isEmpty(signReceiveDto)){
            throw new BusinessException("未指定文书裁执分离相关信息");
        }
        String executeId=signReceiveDto.getCaseSourceId();
       /* String caseId = signReceiveDto.getCaseId();
        if (ObjectUtils.isEmpty(caseId)) {
            throw new BusinessException("未指定案件id");
        }*/
        String documentCatalogCode = signReceiveDto.getDocCategoryCode();
        if(ObjectUtils.isEmpty(documentCatalogCode)){
            throw new BusinessException("未指定文书目录编码");
        }
        String partyId = signReceiveDto.getPartyId();
        //增加送达当事人id处理
        /*CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(caseId);
        String partiesReasonType = caseMainInfo.getCasePartiesReasonType();
        String handleType = caseMainInfo.getHandleType();*/
        Example example=new Example(ExecutePartyInfo.class);
        example.createCriteria().andEqualTo("executeId",signReceiveDto.getCaseSourceId());
        List<ExecutePartyInfo> caseSourcePartyInfos=executePartyInfoMapper.selectByExample(example);
        String partiesReasonType=Constant.STRING_1;
        if(null!=caseSourcePartyInfos&&caseSourcePartyInfos.size()>1){
            partiesReasonType=Constant.STRING_2;
        }
        //查询文书种类
        ConfigBusiParamDocumentInfo configBusiParamDocumentInfo = configBusiParamDocumentInfoService.getDetailByDocumentCatalogCode(documentCatalogCode);
        String kindCode = configBusiParamDocumentInfo.getDocumentKindCode();
        if (ObjectUtils.isEmpty(partyId)) {
            if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(partiesReasonType)
                    && !"GZSHZ".equals(kindCode)
            ) {
                throw new BusinessException("多当事人案件需指定当事人id");
            }
            //Map<String, String> map = casePartiesRecordService.getCasePartyIdNameInfo(caseId);
            //partyId = map.get("partyId");

        }
        ExecuteDocumentRecord executeDocumentRecord = executeDocumentRecordService.getExecuteDocumentRecord(signReceiveDto.getCaseSourceId(), documentCatalogCode, partyId);
        ExecuteAppendixRecord executeAppendixRecord = new ExecuteAppendixRecord();
        int dr = 0;
        if (executeDocumentRecord != null){
            executeAppendixRecord.setExecuteStageCode(executeDocumentRecord.getExecuteStageCode());
            executeAppendixRecord.setExecuteStageName(executeDocumentRecord.getExecuteStageName());
            executeAppendixRecord.setExecuteLinkCode(executeDocumentRecord.getExecuteLinkCode());
            executeAppendixRecord.setExecuteLinkName(executeDocumentRecord.getExecuteLinkName());
            executeDocumentRecord.setDocumentSignstampedStatus(DocumentStatusEnum.CONFIRM_END.getCode());
            //当文书为送达方式及地址确认书更新文书创建时间作为确认时间来使用,后续用于计算有效期限
            if (Constant.STRING_KIND_CODE_SDDZQRS.equals(kindCode)) {
                executeDocumentRecord.setDocumentCreateTime(LocalDateTime.now());
                //送达地址确认书确认时更新送达地址确认书表的状态为1
                Example updateExample = new Example(CaseDocumentSendinfoConfirm.class);
                updateExample.createCriteria().andEqualTo("caseId", executeDocumentRecord.getExecuteId()).andEqualTo("partyId", executeDocumentRecord.getPartyId());
                CaseDocumentSendinfoConfirm caseDocumentSendinfoConfirm = new CaseDocumentSendinfoConfirm();
                caseDocumentSendinfoConfirm.setStatus(Constant.INTEGER_1);
                caseDocumentSendinfoConfirmMapper.updateByExampleSelective(caseDocumentSendinfoConfirm, updateExample);
            }
            executeDocumentRecordMapper.updateByPrimaryKeySelective(executeDocumentRecord);
        }
        executeAppendixRecord.setAppendixTypeId("OFFLINE_SIGN_FILE");
        executeAppendixRecord.setExecuteId(executeId);
        String prefix = signReceiveDto.getAppendixNamePrefix();
        String suffix = signReceiveDto.getAppendixNameSuffix();
        executeAppendixRecord.setAppendixName(prefix+Constant.STRING_POINT+suffix);
        executeAppendixRecord.setAppendixNamePrefix(prefix);
        executeAppendixRecord.setAppendixNameSuffix(suffix);
        executeAppendixRecord.setAppendixUrl(signReceiveDto.getDocUrl());
        executeAppendixRecord.setDocumentCatalogCode(documentCatalogCode);
        executeAppendixRecord.setUploadTime(new Date());
        executeAppendixRecord.setPartyId(partyId);//设置当事人id
        boolean flag=saveExecuteAppendixRecord(executeAppendixRecord);
        if(flag){
            dr=Constant.INTEGER_1;
        }
        return dr;
    }
    @Override
    public boolean saveExecuteAppendixRecord(ExecuteAppendixRecord executeAppendixRecord) {
        try {
            UserDTO userDTO = UserUtil.getUserInfo();
            if (userDTO == null) {
                log.info("登录信息失效或未登录");
                return false;
            }
            executeAppendixRecord.setId(BaseUtil.createUid());
            executeAppendixRecord.setUploadTime(new Date());
            executeAppendixRecord.setUploadUserId(userDTO.getUserId().toString());
            executeAppendixRecord.setUploadUserName(userDTO.getRealName());
            executeAppendixRecord.setIsDelete(Constant.STRING_0);
            executeAppendixRecord.setAppendixStatus(Constant.STRING_1);
            int ret = executeAppendixRecordMapper.insertSelective(executeAppendixRecord);
            if (ret > 0) {
                return true;
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return false;
    }
}